using B.S.NewMedical.Api.Write.Application.Command.Doctor;
using B.S.NewMedical.Domain.Appointment;
using B.S.NewMedical.ErrorCode;
using B.S.NewMedical.Infrastructure;
using B.S.NewMedical.Infrastructure.Interface;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.NewMedical.Api.Write.Application.Handler.Doctor
{
    /// <summary>
    /// 批量删除医生处理器
    /// </summary>
    public class DeleteDoctorsHandler : IRequestHandler<DeleteDoctorsCommand, ApiResult<bool>>
    {
        private readonly IBaseRepository<Domain.Appointment.Doctor> _doctorRepository;
        private readonly MyDbcontext _dbContext;
        private readonly ILogger<DeleteDoctorsHandler> _logger;

        public DeleteDoctorsHandler(
            IBaseRepository<Domain.Appointment.Doctor> doctorRepository,
            MyDbcontext dbContext,
            ILogger<DeleteDoctorsHandler> logger)
        {
            _doctorRepository = doctorRepository;
            _dbContext = dbContext;
            _logger = logger;
        }

        public async Task<ApiResult<bool>> Handle(DeleteDoctorsCommand request, CancellationToken cancellationToken)
        {
            if (request.DoctorIds == null || !request.DoctorIds.Any())
            {
                return new ApiResult<bool>
                {
                    Code = ApiEnum.Fail,
                    Msg = "医生ID列表不能为空",
                    Data = false
                };
            }

            try
            {
                // 开启事务
                using (var transaction = await _dbContext.Database.BeginTransactionAsync(cancellationToken))
                {
                    try
                    {
                        // 查询要删除的医生
                        var doctors = await _dbContext.Set<Domain.Appointment.Doctor>()
                            .Where(d => request.DoctorIds.Contains(d.Id) && !d.IsDeleted)
                            .ToListAsync(cancellationToken);

                        if (!doctors.Any())
                        {
                            return new ApiResult<bool>
                            {
                                Code = ApiEnum.Fail,
                                Msg = "未找到要删除的医生",
                                Data = false
                            };
                        }

                        // 逻辑删除
                        foreach (var doctor in doctors)
                        {
                            doctor.IsDeleted = true;
                            doctor.UpdateTime = DateTime.Now;
                        }

                        // 保存更改
                        await _dbContext.SaveChangesAsync(cancellationToken);

                        // 提交事务
                        await transaction.CommitAsync(cancellationToken);

                        _logger.LogInformation("成功批量删除医生，ID：{DoctorIds}", string.Join(",", request.DoctorIds));

                        return new ApiResult<bool>
                        {
                            Code = ApiEnum.Success,
                            Msg = $"成功删除{doctors.Count}个医生",
                            Data = true
                        };
                    }
                    catch (Exception ex)
                    {
                        // 回滚事务
                        await transaction.RollbackAsync(cancellationToken);
                        _logger.LogError(ex, "批量删除医生失败");
                        throw;
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "批量删除医生时发生异常");
                return new ApiResult<bool>
                {
                    Code = ApiEnum.Error,
                    Msg = "批量删除医生失败：" + ex.Message,
                    Data = false
                };
            }
        }
    }
} 